package com.skycan.plc.adapter.config;

import lombok.Getter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 应用配置加载器
 */
@Getter
public class AppConfig {
    private static final Logger logger = LoggerFactory.getLogger(AppConfig.class);
    private static final AppConfig INSTANCE = new AppConfig();

    private Properties properties;

    // 服务配置
    private int serverPort;

    // 设备轮询间隔(毫秒)
    private long devicePollingInterval;

    private AppConfig() {
        loadProperties();
        initConfig();
    }

    public static AppConfig getInstance() {
        return INSTANCE;
    }

    /**
     * 加载配置文件
     */
    private void loadProperties() {
        properties = new Properties();
        try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream("application.properties")) {
            if (inputStream != null) {
                properties.load(inputStream);
                logger.info("配置文件加载成功");
            } else {
                logger.error("配置文件未找到");
            }
        } catch (IOException e) {
            logger.error("加载配置文件失败", e);
        }
    }

    /**
     * 初始化配置参数
     */
    private void initConfig() {
        serverPort = Integer.parseInt(getProperty("server.port", "8080").trim());
        devicePollingInterval = Long.parseLong(getProperty("device.polling.interval", "5000").trim());
        logger.info("服务配置初始化完成: 端口={}, 轮询间隔={}毫秒", serverPort, devicePollingInterval);
    }

    /**
     * 获取配置属性
     *
     * @param key          配置键
     * @param defaultValue 默认值
     * @return 配置值
     */
    public String getProperty(String key, String defaultValue) {
        String value = properties.getProperty(key, defaultValue);
        return value != null ? value.trim() : defaultValue;
    }
}